#include <ESP8266WiFi.h>
#include "dht11.h"
#include <string>
#include <U8g2lib.h>
#include <Wire.h>

#define SCL 5
#define SDA 4

U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /*clock=*/SCL, /*data=*/SDA, /*reset=*/U8X8_PIN_NONE);   // All Boards without Reset of the Display

const char* ssid = "MERCURY_3394"; //<----修改为自己的
const char* password = "2H2+O2=2H2O"; //<----修改为自己的

const uint16_t port = 6666;
const char *host = "192.168.5.110";
WiFiClient esp8266Client;

#define DHT11_PIN 13

DHT11 dht11(DHT11_PIN);

void setup()
{
  u8g2.begin();
  u8g2.enableUTF8Print(); // enable UTF8 support for the Arduino print() function
  
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  delay(500);
  Serial.print("连接到:");
  Serial.println(ssid);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20)
  {
    delay(500);
  }

  if (i == 21)
  {
    Serial.print("没能连接到:");
    Serial.println(ssid);
    return;
  }

  Serial.print("准备好了！使用的网络IP是: ");
  Serial.println(WiFi.localIP());
  Serial.print("连接到 ");
  Serial.println(host);
  while (!esp8266Client.connect(host, port))
  {
    Serial.println("TCP server端连接失败");
    Serial.println("请等待5秒后重新连接...");
    delay(5000);
    //return;
  }
  Serial.println("TCP server端连接成功");
}

bool read_dht11(float &temp, float &humi)
{
  int ret = dht11.read();
  if (ret == DHTLIB_ERROR_CHECKSUM)
  {
    Serial.println("(E) Checksum failed");
    return false;
  }
  else if (ret == DHTLIB_ERROR_TIMEOUT)
  {
    Serial.println("(E) Read time out");
    return false;
  }

  temp = dht11.getTemperature();
  humi = dht11.getHumidity();
  char tmp[256];
  sprintf(tmp, "Temperature:%.1f, Humidity:%.1f", temp, humi);
  Serial.print(tmp);
  Serial.println();
  return true;
}

void loop()
{
  delay(2000);
  float temp;
  float humi;
  if (read_dht11(temp, humi))
  {
    //向Tcp server发送数据
    char msg[256];
    sprintf(msg, "dht11 %.1f %.1f ", temp, humi);
    Serial.print("发送数据:");
    Serial.print(msg);
    Serial.println();
    esp8266Client.print(msg);

    u8g2.clearBuffer();
    u8g2.setFont(u8g2_font_wqy14_t_gb2312);
    u8g2.setCursor(20, 20);
    u8g2.print("温度: ");
    u8g2.print(temp);
    u8g2.print(" ℃");
    u8g2.setCursor(20, 40);
    u8g2.print("湿度: ");
    u8g2.print(humi);
    u8g2.print(" %");
    u8g2.sendBuffer();
  }
}
